<?php
namespace app\admin\controller;

use app\common\controller\AdminBase;
use app\common\help\ContractHelp;
use think\Db;
use think\Exception;
use think\Log;


class Contract extends AdminBase
{
    private $contract_logic;
    private $config_logic;

    public function _initialize()
    {
        parent::_initialize();
        $this->contract_logic = logic('Contract');
        $this->config_logic = logic('Config');
    }


    /**
     * 合同列表
     * @return mixed
     */
    public function index()
    {
        $where = [];

        //业务类型
        $contract_type_info = $this->contract_logic->getAllTontractType(true);
        $contract_type_id_to_data = $contract_type_info['id_to_data'];
        $contract_type_arr = $contract_type_info['tree_data'];

        /*合同状态*/
        $status = $this->request->param('status', 0, 'intval');
        if (in_array($status, [CONTRACT_STATUS_INIT,CONTRACT_STATUS_RECYCLE,CONTRACT_STATUS_DISCARD])) {
            $where['status'] = $status;
        }
        /*默认0位：发出状态：排除掉废弃合同外的全部合同*/
        if ($status == 0) {
            $where['status'] = [CONTRACT_STATUS_INIT, CONTRACT_STATUS_RECYCLE];
        }

        /*合同年度*/
        $year = $this->request->param('year', 0, 'intval');
        if ($year > 0) {
            $where['year'] = $year;
        }

        //合同编号
        $contract_number = $this->request->param('contract_number', '', 'app\common\controller\ParamFilter::normalParam');
        if (!empty($contract_number)) {
            $where['contract_number'] = $contract_number;
        }

        //客户名称关键字搜索
        $customer_name = $this->request->param('customer_name', '', 'app\common\controller\ParamFilter::normalParam');
        if (!empty($customer_name)) {
            $where['customer_name'] = $customer_name;
        }

        /*项目名称*/
        $project_name = $this->request->param('project_name', '', 'app\common\controller\ParamFilter::normalParam');
        if (!empty($project_name)) {
            $where['project_name'] = $project_name;
        }

        /*营销经理*/
        $sale_manager = $this->request->param('sale_manager', '', 'app\common\controller\ParamFilter::normalParam');
        if (!empty($sale_manager)) {
            $where['sale_manager'] = $sale_manager;
        }

        /*项目负责人*/
        $project_manager = $this->request->param('project_manager', '', 'app\common\controller\ParamFilter::normalParam');
        if (!empty($project_manager)) {
            $where['project_manager'] = $project_manager;
        }

        /*业务类型*/
        $class = $this->request->param('class', 0, 'intval');
        if ($class > 0) {
            $where['class'] = $class;
        }

        /*业务子类型*/
        $type = $this->request->param('type', 0, 'intval');
        if ($type > 0) {
            $where['type'] = $type;
        }

        /*金额区间*/
        $contract_amount_min = $this->request->param('contract_amount_min', 0, '');
        $contract_amount_max = $this->request->param('contract_amount_max', 0, '');
        if ($contract_amount_min <= 0) {
            if ($contract_amount_max > 0) {
                $where['contract_amount_min'] = 0;
                $where['contract_amount_max'] = $contract_amount_max > 999999999 ? 999999999 : $contract_amount_max;
            }
        } else {
            if ($contract_amount_max > 0) {
                if ($contract_amount_max < $contract_amount_min) {
                    $contract_amount_max = 999999999;
                }
                $where['contract_amount_min'] = $contract_amount_min;
                $where['contract_amount_max'] = $contract_amount_max;
            } else {
                $contract_amount_max = 999999999;
                $where['contract_amount_min'] = $contract_amount_min;
                $where['contract_amount_max'] = $contract_amount_max;
            }
        }

        /*区域*/
        $province_id = $this->request->param('province_id', 0, 'intval');
        if ($province_id > 0) {
            $where['province_id'] = $province_id;
        }
        $city_id = $this->request->param('city_id', 0, 'intval');
        if ($city_id > 0) {
            $where['city_id'] = $city_id;
        }
        $district_id = $this->request->param('district_id', 0, 'intval');
        if ($district_id > 0) {
            $where['district_id'] = $district_id;
        }

        //获取星级评定配置
        $star_level_config_info = model('StarLevelConfig')->getList([])->toArray();
        $star_level_config_info = array_column($star_level_config_info['data'], 'star_level');

        /*星级*/
        $star_level = $this->request->param('star_level', 0, 'intval');
        if ($star_level > 0 && in_array($star_level, $star_level_config_info)) {
            $where['star_level'] = $star_level;
        }

        /*合同签订公司*/
        $sign_company_code = $this->request->param('sign_company_code', '', 'trim');
        $sign_company_data = logic('Contract')->getSignCompanyListAndCodeWhere($this->userInfo, $sign_company_code);
        $sign_company_list = $sign_company_data['sign_company_list'];
        $sign_company_code_where = $sign_company_data['sign_company_code_where'];
        if (!empty($sign_company_code_where)) {
            $where['sign_company_code'] = $sign_company_code_where;
        }

        /*项目组*/
        $project_group_id = $this->request->param('project_group_id', 0, 'intval');
        $project_group_list = $this->config_logic->getProjectGroupList();
        if ($project_group_id > 0 && isset($project_group_list[$project_group_id])) {
            $where['project_group_id'] = $project_group_id;
        }

        $contract_list = $this->contract_logic->getList($where, $this->userInfo, $this->pageLimit);
        foreach ($contract_list as $v) {
            if ($v->class > 0) {
                $v->class_name = empty($contract_type_id_to_data[$v->class]['type']) ? '' : $contract_type_id_to_data[$v->class]['type'];
                $v->type_name = empty($contract_type_id_to_data[$v->class]['type']) ? '' : $contract_type_id_to_data[$v->class]['type'];
            }

            if ($v->type > 0) {

            }
        }

        return $this->fetch('index', [
            'contract_list' => $contract_list,
            'year' => $year == 0 ? '' : $year,
            'contract_number' => $contract_number,
            'customer_name' => $customer_name,
            'project_name' => $project_name,
            'sale_manager' => $sale_manager,
            'star_level' => $star_level,
            'project_manager' => $project_manager,
            'class' => $class,
            'type' => $type,
            'status' => $status,
            'contract_amount_min' => $contract_amount_min && $contract_amount_min != 999999999 ? $contract_amount_min : '',
            'contract_amount_max' => $contract_amount_max && $contract_amount_max != 999999999 ? $contract_amount_max : '',
            'province_id' => $province_id,
            'city_id' => $city_id,
            'district_id' => $district_id,
            'star_level' => $star_level,
            'star_level_config_info' => $star_level_config_info,
            'contract_type_arr' => json_encode($contract_type_arr, JSON_UNESCAPED_UNICODE),
            'status_desc' => ContractHelp::contract_status_desc_with_css(),
            'sign_company_list' => $sign_company_list,
            'sign_company_code' => $sign_company_code,
            'project_group_id' => $project_group_id,
            'project_group_list' => $project_group_list,
        ]);
    }


    /**
     * 添加合同
     * @return mixed
     */
    public function add()
    {
        //获取合同签订公司列表
        $sign_company_data = $this->contract_logic->getSignCompanyListAndCodeWhere($this->userInfo);
        $sign_company_list = $sign_company_data['sign_company_list'];
        if (empty($sign_company_list)) {
            $this->error('当前未配置签订公司或您无权获取列表，请联系管理员！');
        }

        //项目分组
        $project_group_list = $this->config_logic->getProjectGroupList();

        if ($this->request->isAjax()) {
            try {
                $data = [];
                /*合同签订公司*/
                $sign_company_code = $this->request->param('sign_company_code', '', 'trim');
                if (!in_array($sign_company_code, array_column($sign_company_list, 'code'))) {
                    exception('指定合同签订公司不存在，或已被删除，请检查！');
                }
                $data['sign_company_code'] = $sign_company_code;

                /*客户id*/
                $customer_id = $this->request->param('customer_id', 0, 'intval');
                if ($customer_id <= 0) {
                    exception('请先选择客户！');
                }
                $data['customer_id'] = $customer_id;

                /*year年份*/
                $year = $this->request->param('year', 0, 'intval');
                if (!preg_match('/\d{4}/', $year)) {
                    exception('请输入正确的四位年份！');
                }
                $data['year'] = $year;

                /*业务类型（大类）*/
                $class = $this->request->param('class', 0, 'intval');
                if ($class <= 0) {
                    exception('请选择业务类型（父类型）！');
                }
                $data['class'] = $class;

                /*业务类型（小类）*/
                $type = $this->request->param('type', 0, 'intval');
                if ($type <= 0) {
                    exception('请选择业务类型（子类型）！');
                }
                $data['type'] = $type;

                /*项目分组*/
                $project_group_id = $this->request->param('project_group_id', 0, 'intval');
                if ($project_group_id > 0 && isset($project_group_list[$project_group_id])) {
                    $data['project_group_id'] = $project_group_id;
                }

                /*服务内容*/
                $service_content = $this->request->param('service_content', '', 'htmlspecialchars');
                if (check_str_is_out_range($service_content, 21000)) {
                    exception('服务内容 内容超出限制（21000 个字）！');
                }
                $data['service_content'] = $service_content;

                /*营销经理*/
                $sale_manager = $this->request->param('sale_manager', '', 'app\common\controller\ParamFilter::normalParam');
                if (empty($sale_manager)) {
                    exception('请填写:营销经理！');
                }
                if (check_str_is_out_range($sale_manager, 10)) {
                    exception('营销经理 内容超出限制（10个字）！');
                }

                $data['sale_manager'] = $sale_manager;

                /*项目名称*/
                $project_name = $this->request->param('project_name', '', 'app\common\controller\ParamFilter::normalParam');
                if (check_str_is_out_range($project_name, 255)) {
                    exception('项目名称 内容超出限制（255 个字）！');
                }
                $data['project_name'] = $project_name;

                /*项目负责人*/
                $project_name = $this->request->param('project_manager', '', 'app\common\controller\ParamFilter::normalParam');
                if (check_str_is_out_range($project_name, 10)) {
                    exception('项目负责人 内容超出限制（10 个字）！');
                }
                $data['project_manager'] = $project_name;

                /*合同金额*/
                $contract_amount = $this->request->param('contract_amount', '', 'trim');
                if (!empty($contract_amount)) {
                    if (!is_numeric($contract_amount)) {
                        exception('请填写正确的合同金额，例如：5000 ！');
                    }

                    if ($contract_amount > 999999999) {
                        exception('抱歉，您填写的合同金额过大，请填写正确的金额数据 ！');
                    }
                }
                $data['contract_amount'] = $contract_amount;

                /*是否含税*/
                $is_include_tax = $this->request->param('is_include_tax', 1, 'intval');
                if (!in_array($is_include_tax, [0, 1])) {
                    $is_include_tax = 1;
                }
                $data['is_include_tax'] = $is_include_tax;

                /*合同领取人*/
                $contract_receiver = $this->request->param('contract_receiver', '', 'app\common\controller\ParamFilter::normalParam');
                if (empty($contract_receiver)) {
                    exception('请填写: 合同领取人！');
                }
                if (check_str_is_out_range($contract_receiver, 10)) {
                    exception('合同领取人 内容超出限制（10个字）！');
                }
                $data['contract_receiver'] = $contract_receiver;

                $res = $this->contract_logic->submitContract($data, $this->userInfo);
                if ($res) {
                    return ajax_return_adv('添加成功！');
                } else {
                    exception('添加失败！');
                }
            } catch (Exception $e) {
                return ajax_return_error($e->getMessage());
            }
        }

        //业务类型
        $contract_type_arr = $this->contract_logic->getAllTontractType();

        return $this->fetch('add', [
            'contract_type_arr' => json_encode($contract_type_arr, JSON_UNESCAPED_UNICODE),
            'sign_company_list' => $sign_company_list,
            'project_group_list' => $project_group_list,
        ]);
    }

    /**
     * 获取最新的合同编号序号
     */
    public function get_newest_sn()
    {
        if ($this->request->isAjax()) {
            $sign_company_list = $this->contract_logic->getSignCompanyList();
            if (empty($sign_company_list)) {
                return ajax_return_error('请先配置合同签订公司！');
            }

            $code = $this->request->param('code', '', 'trim');
            if (empty($code)) {
                return ajax_return_error('请选择合同签订公司');
            }

            if (!in_array($code, array_column($sign_company_list, 'code'))) {
                return ajax_return_error('指定合同签订公司不存在，或已被删除，请检查！');
            }

            $newest_number = $this->contract_logic->getContractNumber($code, date('Y'))['serial_number'];
            $newest_number = sprintf("%04d", $newest_number);
            return ajax_return_adv($newest_number);
        }
    }


    /**
     * 编辑合同
     * @return mixed
     */
    public function edit()
    {
        $id = $this->request->param('id', 0, 'intval');
        if ($id <= 0) {
            $this->error('请指定合同！');
        }
        $contract_info = $this->contract_logic->getInfo([
            'id' => $id,
        ]);

        if ($contract_info['status'] == CONTRACT_STATUS_DISCARD) {
            $this->error('废弃状态下的合同不能再被操作！');
        }

        //项目分组
        $project_group_list = $this->config_logic->getProjectGroupList();

        if ($this->request->isAjax() && $id > 0) {
            try {
                $data = [];

                /*客户id*/
                $customer_id = $this->request->param('customer_id', 0, 'intval');
                if ($customer_id <= 0) {
                    exception('请先选择客户！');
                }
                $data['customer_id'] = $customer_id;

                /*业务类型（大类）*/
                $class = $this->request->param('class', 0, 'intval');
                if ($class <= 0) {
                    exception('请选择业务类型（父类型）！');
                }
                $data['class'] = $class;

                /*业务类型（小类）*/
                $type = $this->request->param('type', 0, 'intval');
                if ($type <= 0) {
                    exception('请选择业务类型（子类型）！');
                }
                $data['type'] = $type;

                /*项目分组*/
                $project_group_id = $this->request->param('project_group_id', 0, 'intval');
                if (isset($project_group_list[$project_group_id])) {
                    $data['project_group_id'] = $project_group_id;
                }

                /*服务内容*/
                $service_content = $this->request->param('service_content', '', 'htmlspecialchars');
                if (check_str_is_out_range($service_content, 21000)) {
                    exception('服务内容 内容超出限制（21000 个字）！');
                }
                $data['service_content'] = $service_content;

                /*营销经理*/
                $sale_manager = $this->request->param('sale_manager', '', 'app\common\controller\ParamFilter::normalParam');
                if (empty($sale_manager)) {
                    exception('请填写:营销经理！');
                }
                if (check_str_is_out_range($sale_manager, 10)) {
                    exception('营销经理 内容超出限制（10个字）！');
                }

                $data['sale_manager'] = $sale_manager;

                /*项目名称*/
                $project_name = $this->request->param('project_name', '', 'app\common\controller\ParamFilter::normalParam');
                if (check_str_is_out_range($project_name, 255)) {
                    exception('项目名称 内容超出限制（255 个字）！');
                }
                $data['project_name'] = $project_name;

                /*项目负责人*/
                $project_name = $this->request->param('project_manager', '', 'app\common\controller\ParamFilter::normalParam');
                if (check_str_is_out_range($project_name, 10)) {
                    exception('项目负责人 内容超出限制（10 个字）！');
                }
                $data['project_manager'] = $project_name;

                /*合同金额*/
                $contract_amount = $this->request->param('contract_amount', '', 'trim');
                if (!empty($contract_amount)) {
                    if (!is_numeric($contract_amount)) {
                        exception('请填写正确的合同金额，例如：5000 ！');
                    }

                    if ($contract_amount > 999999999) {
                        exception('抱歉，您填写的合同金额过大，请填写正确的金额数据 ！');
                    }
                }
                $data['contract_amount'] = $contract_amount;

                /*是否含税*/
                $is_include_tax = $this->request->param('is_include_tax', 1, 'intval');
                if (!in_array($is_include_tax, [0, 1])) {
                    $is_include_tax = 1;
                }
                $data['is_include_tax'] = $is_include_tax;

                /*合同领取人*/
                $contract_receiver = $this->request->param('contract_receiver', '', 'app\common\controller\ParamFilter::normalParam');
                if (empty($contract_receiver)) {
                    exception('请填写: 合同领取人！');
                }
                if (check_str_is_out_range($contract_receiver, 10)) {
                    exception('合同领取人 内容超出限制（10个字）！');
                }
                $data['contract_receiver'] = $contract_receiver;

                $res = $this->contract_logic->submitContract($data, $this->userInfo, $id);
                if ($res) {
                    return ajax_return_adv('修改成功！');
                } else {
                    exception('修改失败！');
                }
            } catch (Exception $e) {
                return ajax_return_error($e->getMessage());
            }
        }
        //业务类型
        $contract_type_arr = $this->contract_logic->getAllTontractType();

        return $this->fetch('edit', [
            'info' => $contract_info,
            'contract_type_arr' => json_encode($contract_type_arr, JSON_UNESCAPED_UNICODE),
            'project_group_list' => $project_group_list,
        ]);
    }

    /**
     * 删除合同 （可批量）
     */
    public function delete()
    {
        $ids = $this->request->param('ids', '', 'trim');
        $ids = explode(',', $ids);
        $ids = array_unique(array_filter(array_map(function($v){
            return (int)$v;
        }, $ids)));

        if ($this->request->isAjax()) {
            if (empty($ids)) {
                return ajax_return_adv('未进行任何删除！');
            }
            Db::startTrans();
            try {
                if (!$this->contract_logic->deleteData($ids)) {
                    exception('请重试');
                }
                Db::commit();
                return ajax_return_adv('删除成功！');
            } catch (Exception $e) {
                Db::rollback();
                return ajax_return_error('删除失败('.$e->getMessage().')！');
            }
        }
    }

    /**
     * 查看合同详情
     */
    public function info()
    {
        //项目分组
        $project_group_list = $this->config_logic->getProjectGroupList();

        $id = $this->request->param('id', 0, 'intval');
        if ($id <= 0) {
            $this->error('请指定合同！');
        }
        $info = $this->contract_logic->getInfo([
            'id' => $id,
        ]);
        return $this->fetch('info', [
            'info' => $info,
            'project_group_list' => $project_group_list,
        ]);
    }

    /**
     * 回收合同
     */
    public function recycle()
    {
        $id = $this->request->param('id', 0, 'intval');
        $contract_number = $this->request->param('number', '', 'trim');

        //项目分组
        $project_group_list = $this->config_logic->getProjectGroupList();

        if ($this->request->isAjax()) {
            try {
                if ($id <= 0) {
                    exception(('请先指定要回收的合同！'));
                }
                /*回收时间*/
                $take_back_time = $this->request->param('take_back_time', '', 'trim');
                if (empty($take_back_time)) {
                    exception('请填写交回时间');
                }
                //检查是否是时间格式:
                $take_back_time = strtotime($take_back_time);
                if ($take_back_time <= 0) {
                    exception('请填写正确的时间信息！');
                }

                $scanning_file = $this->request->param('scanning_file', '', 'app\common\controller\ParamFilter::normalParam');

                /*交回人员*/
                $take_back_user = $this->request->param('take_back_user', '', 'trim');
                if (empty($take_back_user)) {
                    exception('请填写交回人员！');
                }

                /*项目分组*/
                $project_group_id = $this->request->param('project_group_id', 0, 'intval');

                $data = [
                    'take_back_user' => $take_back_user,
                    'take_back_time' => $take_back_time,
                    'take_back_operate_time' => time(),
                    'take_back_operate_uid' => $this->userInfo['id'],
                    'scanning_file' => $scanning_file,
                    'status' => CONTRACT_STATUS_RECYCLE,
                ];

                if ($project_group_id > 0 && isset($project_group_list[$project_group_id])) {
                    $data['project_group_id'] = $project_group_id;
                }

                $res = $this->contract_logic->doRecycle($id, $data);
                if (!$res) {
                    exception('操作失败，请重试！');
                }
                return ajax_return_adv('操作成功！');
            } catch (Exception $e) {
                return ajax_return_error($e->getMessage());
            }
        }

        $contract_info = $this->contract_logic->getSimpleInfo([
            'id' => $id
        ], 'project_group_id');
        if (empty($contract_info)) {
            exception('指定合同不存在，或已被删除，请检查！');
        }

        return $this->fetch('recycle', [
            'id' => $id,
            'contract_number' => $contract_number,
            'project_group_id' => isset($contract_info['project_group_id']) ? $contract_info['project_group_id'] : 0,
            'project_group_list' => $project_group_list,
        ]);
    }


    /**
     * 作废合同
     */
    public function discard()
    {
        $id = $this->request->param('id', 0, 'intval');
        $contract_number = $this->request->param('number', '', 'trim');

        if ($this->request->isAjax()) {
            try {
                if ($id <= 0) {
                    exception(('请先指定要作废的合同！'));
                }

                /*作废原因*/
                $discard_reason = $this->request->param('discard_reason', '', 'trim');
                if (empty($discard_reason)) {
                    exception('请填写作废原因！');
                }

                $data = [
                    'discard_reason' => $discard_reason,
                    'discard_operate_time' => time(),
                    'discard_operate_uid' => $this->userInfo['id'],
                    'status' => CONTRACT_STATUS_DISCARD,
                ];

                $res = $this->contract_logic->doDiscard($id, $data);
                if (!$res) {
                    exception('操作失败，请重试！');
                }
                return ajax_return_adv('操作成功！');
            } catch (Exception $e) {
                return ajax_return_error($e->getMessage());
            }
        }

        return $this->fetch('discard', [
            'id' => $id,
            'contract_number' => $contract_number,
        ]);
    }

    /**
     * 上传文件合同扫描件
     */
    public function upload_scanning()
    {
        if ($this->request->isPost()) {
            try {
                //获取合同编号，用于为扫描件命名
                $contract_number = $this->request->param('contract_number', '', 'trim');
                if (empty($contract_number)) {
                    exception('请指定合同！');
                }

                //检查合同是否存在
                if (!$this->contract_logic->chechkContractIsExists($contract_number)) {
                    exception('指定合同不存在，或已被删除，请检查！');
                }

                $upload_logic = logic('Upload');
                $upload_logic->setUploadExt(['pdf']);
                $upload_logic->setMimeType(['application/pdf']);
                $upload_logic->setUploadPath(UPLOAD_FILE_PATH . '/contract_file');
                $upload_logic->setfileEachLimitSize(10);
                $res = $upload_logic->uploadFile($contract_number, 'pdf');//成功后，为上传的文件路径，此处一次只能上传一张
                if ($res && is_array($res)) {
                    Log::record('文件上传成功：' . $res[0]);
                    $url = str_replace(UPLOAD_FILE_PATH, '', $res[0]);
                    return ajax_return_adv($url);
                } else {
                    exception('上传失败');
                }
            } catch (Exception $e) {
                return ajax_return_error($e->getMessage());
            }
        }
    }

    /**
     * 下载扫描件
     */
    public function down_scnning_file()
    {
        $file_url = $this->request->param('file_url', '', '');
        $file_urldisk = UPLOAD_FILE_PATH . $file_url;
        if (file_exists($file_urldisk)) {
            //获取文件名：
            $filename =  substr(strrchr($file_url,'/'),1);
            header('Content-Type: application-x/force-download');
            header('Content-Disposition: attachment; filename="' . basename($filename) .'"');
            header('Content-length: ' . filesize($file_urldisk));

            // for IE6
            if (false === strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE 6')) {
                header('Cache-Control: no-cache, must-revalidate');
            }
            header('Pragma: no-cache');

            // read file content and output
            return readfile($file_urldisk);
        } else {
            return '文件不存在，请检查！';
        }
    }

    /**
     * 打包下载记录
     */
    public function pack_download_record()
    {
        $download_record_model = model('DownloadRecord');

        $where = [];

        /*项目组*/
        $project_group_id = $this->request->param('project_group_id', 0, 'intval');
        $project_group_list = $this->config_logic->getProjectGroupList();
        if ($project_group_id > 0 && isset($project_group_list[$project_group_id])) {
            $where['project_group_id'] = $project_group_id;
        }

        /*回收开始时间*/
        $recycle_begin = $this->request->param('recycle_begin', '', 'trim');
        if (!empty($recycle_begin)) {
            $where['recycle_begin'] = $recycle_begin;
        }

        /*回收截止时间*/
        $recycle_end = $this->request->param('recycle_end', '', 'trim');
        if (!empty($recycle_end)) {
            $where['recycle_end'] = $recycle_end;
        }

        $list = $download_record_model->getList($where, $this->pageLimit);
        foreach ($list as $v) {
            switch ($v->status) {
                case PACK_STATUS_BEGIN:
                    $v->status_desc = '打包中';
                    break;
                case PACK_STATUS_SUCCESS:
                    $v->status_desc = '打包成功';
                    break;
                case PACK_STATUS_FAILED:
                    $v->status_desc = $v->errmsg;
                    break;
                default:
                    $v->status_desc = '';
            }
        }

        return $this->fetch('pack_download_record', [
            'list' => $list,
            'project_group_list' => $project_group_list,
            'project_group_id' => $project_group_id,
            'recycle_begin' => $recycle_begin,
            'recycle_end' => $recycle_end,
        ]);
    }

    /**
     * 打包扫描件
     */
    public function pack_scanning_file()
    {
        $project_group_list = $this->config_logic->getProjectGroupList();

        if ($this->request->isAjax()) {
            try {
                $project_group_id = $this->request->param('project_group_id', 0, 'intval');
                if ($project_group_id <= 0) {
                    exception('请指定项目组');
                }

                if (!isset($project_group_list[$project_group_id])) {
                    exception('指定项目组不存在，或已被删除！');
                }

                /*回收开始时间*/
                $recycle_begin = $this->request->param('recycle_begin', '', 'trim');
                if (empty($recycle_begin)) {
                    exception('请指定回收合同的起始时间！');
                }
                $recycle_begin = $recycle_begin . ' 00:00:01';
                $recycle_begin = strtotime($recycle_begin);
                if ($recycle_begin <= 0) {
                    exception('起始时间格式错误！');
                }

                /*回收截止时间*/
                $recycle_end = $this->request->param('recycle_end', '', 'trim');
                if (empty($recycle_end)) {
                    exception('请指定回收合同的截止时间！');
                }
                $recycle_end = $recycle_end . ' 23:59:59';
                $recycle_end = strtotime($recycle_end);
                if ($recycle_end <= 0) {
                    exception('起始时间格式错误！');
                }
                if ($recycle_end < $recycle_begin) {
                    exception('截止时间不能小于开始时间！');
                }

                $res = $this->contract_logic->packContractScanningFiles($project_group_id, $recycle_begin, $recycle_end);
                return ajax_return_adv($res);

            } catch (Exception $e) {
                return ajax_return_error($e->getMessage());
            }
        }

        return $this->fetch('pack_scanning_file', [
            'project_group_list' => $project_group_list,
        ]);
    }

    /**
     * 删除打包记录，删除后，再次下载会重复下载
     */
    public function delete_pack_record()
    {
        $id = $this->request->param('id', 0, 'intval');
        if ($this->request->isAjax()) {
            try {
                if ($id <= 0) {
                    exception('请指定要删除的记录！');
                }
                $res = $this->contract_logic->deletePackRecord($id);
                if (!$res) {
                    exception('删除失败，请稍后重试！');
                }

                return ajax_return_adv('删除成功');
            } catch (Exception $e) {
                return ajax_return_error($e->getMessage());
            }
        }
    }

    /**
     * 客户导入使用 Excel模板
     */
    public function import_contracts()
    {

        $key = config('admin_upload_key');

        if ($this->request->isPost()) {
            $t      = $this->request->param('t', '');
            $token  = $this->request->param('token', '');

            if ($token != md5($key . '+' .$t)) {
                return ajax_return_error('error request!');
            }

            ini_set('memory_limit', '520M'); //内存限制
            set_time_limit(0); //超时限制
            $this->request->file();

            try {
                $res= $this->contract_logic->batchImportData($this->userInfo);
                return ajax_return_adv($res);
            } catch (Exception $e) {
                return ajax_return_error($e->getMessage());
            }
        }

        $t = time();
        $batch_token = md5($key . '+' .$t);
        return $this->fetch('import', [
            'token' => $batch_token,
            't'     => $t,
        ]);
    }

    /**
     * 列表导出
     */
    public function export_contracts()
    {
        $where = [];

        //业务类型
        $contract_type_info = $this->contract_logic->getAllTontractType(true);
        $contract_type_id_to_data = $contract_type_info['id_to_data'];
        $contract_type_arr = $contract_type_info['tree_data'];

        /*合同状态*/
        $status = $this->request->param('status', 0, 'intval');
        if (in_array($status, [CONTRACT_STATUS_INIT,CONTRACT_STATUS_RECYCLE,CONTRACT_STATUS_DISCARD])) {
            $where['status'] = $status;
        }
        /*默认0位：发出状态：排除掉废弃合同外的全部合同*/
        if ($status == 0) {
            $where['status'] = [CONTRACT_STATUS_INIT, CONTRACT_STATUS_RECYCLE];
        }

        /*合同年度*/
        $year = $this->request->param('year', 0, 'intval');
        if ($year > 0) {
            $where['year'] = $year;
        }

        //合同编号
        $contract_number = $this->request->param('contract_number', '', 'app\common\controller\ParamFilter::normalParam');
        if (!empty($contract_number)) {
            $where['contract_number'] = $contract_number;
        }

        //客户名称关键字搜索
        $customer_name = $this->request->param('customer_name', '', 'app\common\controller\ParamFilter::normalParam');
        if (!empty($customer_name)) {
            $where['customer_name'] = $customer_name;
        }

        /*项目名称*/
        $project_name = $this->request->param('project_name', '', 'app\common\controller\ParamFilter::normalParam');
        if (!empty($project_name)) {
            $where['project_name'] = $project_name;
        }

        /*营销经理*/
        $sale_manager = $this->request->param('sale_manager', '', 'app\common\controller\ParamFilter::normalParam');
        if (!empty($sale_manager)) {
            $where['sale_manager'] = $sale_manager;
        }

        /*项目负责人*/
        $project_manager = $this->request->param('project_manager', '', 'app\common\controller\ParamFilter::normalParam');
        if (!empty($project_manager)) {
            $where['project_manager'] = $project_manager;
        }

        /*业务类型*/
        $class = $this->request->param('class', 0, 'intval');
        if ($class > 0) {
            $where['class'] = $class;
        }

        /*业务子类型*/
        $type = $this->request->param('type', 0, 'intval');
        if ($type > 0) {
            $where['type'] = $type;
        }

        /*金额区间*/
        $contract_amount_min = $this->request->param('contract_amount_min', 0, '');
        $contract_amount_max = $this->request->param('contract_amount_max', 0, '');
        if ($contract_amount_min <= 0) {
            if ($contract_amount_max > 0) {
                $where['contract_amount_min'] = 0;
                $where['contract_amount_max'] = $contract_amount_max > 999999999 ? 999999999 : $contract_amount_max;
            }
        } else {
            if ($contract_amount_max > 0) {
                if ($contract_amount_max < $contract_amount_min) {
                    $contract_amount_max = 999999999;
                }
                $where['contract_amount_min'] = $contract_amount_min;
                $where['contract_amount_max'] = $contract_amount_max;
            } else {
                $contract_amount_max = 999999999;
                $where['contract_amount_min'] = $contract_amount_min;
                $where['contract_amount_max'] = $contract_amount_max;
            }
        }

        /*区域*/
        $province_id = $this->request->param('province_id', 0, 'intval');
        if ($province_id > 0) {
            $where['province_id'] = $province_id;
        }
        $city_id = $this->request->param('city_id', 0, 'intval');
        if ($city_id > 0) {
            $where['city_id'] = $city_id;
        }
        $district_id = $this->request->param('district_id', 0, 'intval');
        if ($district_id > 0) {
            $where['district_id'] = $district_id;
        }

        //获取星级评定配置
        $star_level_config_info = model('StarLevelConfig')->getList([])->toArray();
        $star_level_config_info = array_column($star_level_config_info['data'], 'star_level');

        /*星级*/
        $star_level = $this->request->param('star_level', 0, 'intval');
        if ($star_level > 0 && in_array($star_level, $star_level_config_info)) {
            $where['star_level'] = $star_level;
        }

        /*合同签订公司*/
        $sign_company_code = $this->request->param('sign_company_code', '', 'trim');
        $sign_company_data = logic('Contract')->getSignCompanyListAndCodeWhere($this->userInfo, $sign_company_code);
        $sign_company_list = $sign_company_data['sign_company_list'];
        $sign_company_cide_name_map = [];
        foreach ($sign_company_list as $v) {
            $sign_company_cide_name_map[$v['code']] = $v['sign_company'];
        }
        $sign_company_code_where = $sign_company_data['sign_company_code_where'];
        if (!empty($sign_company_code_where)) {
            $where['sign_company_code'] = $sign_company_code_where;
        }

        /*项目组*/
        $project_group_id = $this->request->param('project_group_id', 0, 'intval');
        $project_group_list = $this->config_logic->getProjectGroupList();
        if ($project_group_id > 0 && isset($project_group_list[$project_group_id])) {
            $where['project_group_id'] = $project_group_id;
        }

        $contract_list = $this->contract_logic->getListForExport($where, $this->userInfo, 100000);
        foreach ($contract_list as &$v) {
            /*合同签订公司*/
            $v['sign_company_name'] = empty($sign_company_cide_name_map[$v['sign_company_code']]) ? '' : $sign_company_cide_name_map[$v['sign_company_code']];
            /*业务类型*/
            $v['class'] = ($v['class'] > 0 && !empty($contract_type_id_to_data[$v['class']]['type'])) ? $contract_type_id_to_data[$v['class']]['type'] : '';
            $v['type'] = ($v['type'] > 0 && !empty($contract_type_id_to_data[$v['type']]['type'])) ? $contract_type_id_to_data[$v['type']]['type'] : '';
            /*项目组*/
            $v['project_group'] = empty($project_group_list[$v['project_group_id']]) ? '' : $project_group_list[$v['project_group_id']];
            /*是否含税*/
            $v['is_include_tax'] = $v['is_include_tax'] ? '是' : '否';
            /*收回合同的时间*/
            $v['take_back_time'] = $v['take_back_time'] > 0 ? date('Y-m-d H:i:s', $v['take_back_time']) : '';
            /*服务内容解码*/
            $v['service_content'] = decode_rich_text_content($v['service_content']);
        }

        $file_name = "contract-list-" . date('ymd');
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="' . $file_name . '.csv"');
        header('Cache-Control: max-age=0');
        header('Set-Cookie: fileDownload=true; path=/');//使用jQuery.fileDownload.js 时必须添加该头，否则会导致回调函数失效

        // 打开PHP文件句柄，php://output 表示直接输出到浏览器
        $fp = fopen('php://output', 'a');

        // 输出Excel列名信息
        $head = [
            '合同编号',
            '合同签订公司',
            '合同年份',
            '客户编号',
            '客户名称',
            '项目状态',
            '业务类型（大类）',
            '业务类型（小类）',
            '项目组',
            '服务内容',
            '营销经理',
            '项目名称',
            '项目负责人',
            '合同金额',
            '是否含税',
            '合同领取人',
            '收回合同的人员',
            '收回合同的时间',
            '录入合同的时间',
        ];

        foreach ($head as $i => $v) {
            // CSV的Excel支持GBK编码，一定要转换，否则乱码
            $head[$i] = iconv('utf-8', 'gbk', $v);
        }

        //将数据通过fputcsv写到文件句柄
        fputcsv($fp, $head);


        $count = 0;// 计数器
        $limit = 100000; // 每隔$limit行，刷新一下输出buffer，不要太大，也不要太小

        // 逐行取出数据，不浪费内存
        foreach ($contract_list as $v) {
            $count++;
            if ($limit == $count) { //刷新一下输出buffer，防止由于数据过多造成问题
                ob_flush();
                flush();
                $count = 0;
            }

            //将每一行数据处理成跟表头对应的形式
            $tmp = $v;
            foreach ($tmp as $k_field => &$v_field) {
                //防止数字被科学计数法显示丢失
                if (is_numeric($v_field) && strlen($v_field) > 8) {
                    $v_field = $v_field."\t";
                }

                $v_field = iconv('utf-8', 'gbk', $v_field);
            }

            $row = [
                $tmp['contract_number'],
                $tmp['sign_company_name'],
                $tmp['year'],
                $tmp['customer_number'],
                $tmp['customer_name'],
                $tmp['status_desc'],
                $tmp['class'],
                $tmp['type'],
                $tmp['project_group'],
                $tmp['service_content'],
                $tmp['sale_manager'],
                $tmp['project_name'],
                $tmp['project_manager'],
                $tmp['contract_amount'],
                $tmp['is_include_tax'],
                $tmp['contract_receiver'],
                $tmp['take_back_user'],
                $tmp['take_back_time'],
                $tmp['create_time'],
            ];

            fputcsv($fp, $row);
        }
    }
}
